/* api */
import { deleteDingtalkAssistantDoc, getDingtalkAssistantDoc, getDingtalkAssistantDocStudy } from '@src/api/AIApi'
/* components */
import { SettingGPTViewTable } from '@src/modules/setting/gpt/components'
/* enum */
import ComponentNameEnum from '@model/enum/ComponentNameEnum'
import { SettingGPTQuestionTypeEnum } from '@src/modules/setting/gpt/model'
/* hooks */
import { useSettingListPage, useSettingListTable } from '@src/modules/setting/gpt/hooks'
/* model */
import Page from '@model/Page'
import MsgModel from '@model/MsgModel'
import { SettingDingtalkDocFields } from '@gpt/views/edit/dingtalk-assistant/model'
/* vue */
import { defineComponent, PropType, Ref, ref } from 'vue'
/* types */
import { SettingGPTLogItemType, SettingGPTQuestionItemType } from '@src/modules/setting/gpt/types'
import Column from '@model/types/Column'
/* util */
import { 
  DingtalkOpenAuthBaseParams, 
  DingtalkOpenAuthStatusEnum, 
  DingtalkOpenAuthTypeEnum, 
  getRootWindow, 
  isEmpty, 
  isFalsy, 
  uuid 
} from 'pub-bbx-utils'
import { settingListFieldsToColumns } from '@gpt/utils'
import { message } from '@src/util/message'
import { getLocalesOssUrl } from '@src/util/assets'
/* types */
import { ShbDingtalkAssistantDoc } from '@gpt/views/edit/dingtalk-assistant/types'
import { DeleteDingtalkAssistantDocModel } from '@model/param/in/AI'
import { openDingtalkAuth } from '@src/util/dd/auth'
import { DingtalkAuthTypeItem } from '@model/dingtalk'

const docEmptyIcon = getLocalesOssUrl('/ai/ai_doc_empty.png')

type SettingGPTViewTableComponent = InstanceType<typeof SettingGPTViewTable>;

enum SettingGPTDingtalkAssistantDocTableEventEnum {
  Add = 'add',
  Delete = 'delete',
  Edit = 'edit'
}

export default defineComponent({
  name: ComponentNameEnum.SettingGPTDingtalkAssistantDocTable,
  props: {
    isShowDelete: {
      type: Boolean,
      default: true
    },
    showTableSelection: {
      type: Boolean,
      default: false
    },
    onDelete: {
      type: Function
    },
    onEdit: {
      type: Function
    },
    onAdd: {
      type: Function
    }
  },
  data() {
    return {
      key: uuid(),
      value: [] as ShbDingtalkAssistantDoc[],
      showPagination: false,
      loading: false
    }
  },
  computed: {
    columns(): Column[] {
      const fields = SettingDingtalkDocFields
      return settingListFieldsToColumns(fields)
    },
    settingGPTViewTableComponent(): SettingGPTViewTableComponent {
      return this.$refs.SettingGPTViewTable as SettingGPTViewTableComponent
    },
    attrs(): Record<string, any> {
      return {
        // 指令
        directives: [
          {
            name: 'loading',
            value: this.loading
          }
        ]
      }
    }
  },
  watch: {
    active() {
      this.clearSelection()
    }
  },
  mounted() {
    this.initialize()
  },
  methods: {
    async initialize() {
      try {
        
        this.loading = true
        
        const docUrl = await this.getDingtalkAssistantDoc()
        if (isEmpty(docUrl)) {
          console.warn('docUrl is empty')
          return
        }
        
        const docStudyList = await this.getDingtalkAssistantDocStudy()
        if (isEmpty(docStudyList)) {
          
          console.warn('docStudyList is empty')
          
          const docValue: ShbDingtalkAssistantDoc = {
            docUrl: docUrl || ''
          }
        
          this.value = [docValue]
          
          return
        }
        
        const _docStudyList = docStudyList || []
        const docNum = _docStudyList.length
        
        const studyDoneList = _docStudyList.filter(item => {
          return ['DONE', '学习完成'].includes(item.statusName)
        })
        const studyNum = studyDoneList.length
        
        const failList = _docStudyList.filter(item => {
          return ['FAIELD', '失败'].includes(item.statusName)
        })
        const failNum = failList.length
        
        const learningList = _docStudyList.filter(item => {
          return ['LEARNING', '学习中'].includes(item.statusName)
        })
        const learningNum = learningList.length
        
        const docValue: ShbDingtalkAssistantDoc = {
          docUrl: docUrl || '',
          docNum,
          studyNum,
          learningNum,
          failNum
        }
      
        this.value = [docValue]

      } catch (error) {
        console.error('initialize error', error)
      } finally {
        this.$nextTick(() => {
          this.loading = false
        })
      }
    },
    async getDingtalkAssistantDoc() {
      try {
        
        const docResult = await getDingtalkAssistantDoc()
        const isFail = MsgModel.isFail(docResult)
        if (isFail) {
          // 知识库为空
          const isEmpty = docResult.status == 1005
          if (isEmpty) {
            return
          }
          message.error(docResult.message)
          return
        }
        
        const docUrl = docResult.data || ''
        
        return docUrl
        
      } catch (error) {
        console.error('getDingtalkAssistantDoc error', error)
      }
    },
    async getDingtalkAssistantDocStudy() {
      try {
        
        const authCode = await this.openDingtalkAuth()
        const params = {
          assistantId: '',
          authCode
        }
        
        const docResult = await getDingtalkAssistantDocStudy(params)
        const isFail = MsgModel.isFail(docResult)
        if (isFail) {
          message.error(docResult.message)
          return
        }
        
        const docStudyList = docResult.data || []
        
        return docStudyList
        
      } catch (error) {
        console.error('getDingtalkAssistantDocStudy error', error)
      }
    },
    async openDingtalkAuth() {
      
      console.log('openDingtalkAuth')
      
      const params: DingtalkOpenAuthBaseParams = {
        rpcScope: 'Assistant.Knowledge.Write',
        type: DingtalkOpenAuthTypeEnum.Personal
      }
      
      console.log('openDingtalkAuth params: ', params)
      
      await openDingtalkAuth(params as DingtalkAuthTypeItem)
      
      const authCode = ''
      return authCode
    },
    async deleteDingtalkAssistantDoc() {
      try {
        
        const authCode = await this.openDingtalkAuth()
        const params: DeleteDingtalkAssistantDocModel = {
          authCode
        }
        
        const deleteResult = await deleteDingtalkAssistantDoc(params)
        if (MsgModel.isFail(deleteResult)) {
          message.error(deleteResult.message)
          return
        }
        
        this.value = []
        this.initialize()
        
      } catch (error) {
        console.error('deleteDingtalkAssistantDoc error', error)
      }
    },
    clearSelection() {
      this.settingGPTViewTableComponent.clearSelection()
    },
    onAddHandler() {
      this.$emit(SettingGPTDingtalkAssistantDocTableEventEnum.Add)
    },
    rerender() {
      this.$nextTick(() => {
        this.key = uuid()
      })
    },
    renderEmpty() {
      return (
        <div class="setting-gpt-dingtalk-assistant-doc-table-empty">
          <div class="setting-gpt-dingtalk-assistant-doc-table-empty-icon-block">
            <img
              class="setting-gpt-dingtalk-assistant-doc-table-empty-icon"
              src={docEmptyIcon}
            />
          </div>
          <div class="setting-gpt-dingtalk-assistant-doc-table-empty-text">
            暂无学习内容
          </div>
          <div>
            <el-button
              type="info"
              plain
              onClick={this.onAddHandler}
            >
              添加知识库
            </el-button>
          </div>
        </div>
      )
    }
  },
  render() {
    
    const attrs = this.attrs
    
    return (
      <div 
        class={ComponentNameEnum.SettingGPTDingtalkAssistantDocTable}
        {...attrs}
      >
        <SettingGPTViewTable
          ref="SettingGPTViewTable"
          key={this.key}
          columns={this.columns}
          data={this.value}
          showPagination={this.showPagination}
          showTableSelection={this.showTableSelection}
        >
          <div slot="empty">
            {this.renderEmpty()}
          </div>
        </SettingGPTViewTable>
      </div>
    )
  }
})